<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>地址管理</p>
    </header>
    
    <!-- 地址列表部分 -->
    <ul class="addresslist">
      <li v-for="item in deliveryAddressArr" :key="item.id">
        <div class="addresslist-left" @click="setDeliveryAddress(item)">
          <h3>{{item.contactName}} {{getGenderText(item.contactSex)}} {{item.contactTel}}</h3>
          <p>{{item.address}}</p>
        </div>
        <div class="addresslist-right">
          <i class="fa fa-edit" @click="editUserAddress(item.id)"></i>
          <i class="fa fa-remove" @click="removeUserAddress(item.id)"></i>
        </div>
      </li>
    </ul>
    
    <!-- 新增地址部分 -->
    <div class="addbtn" @click="toAddUserAddress">
      <i class="fa fa-plus-circle"></i>
      <p>新增收货地址</p>
    </div>
    
    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'UserAddress',
  data() {
    return {
      businessId: this.$route.query.businessId,
      user: {},
      deliveryAddressArr: []
    }
  },
  created() {
    this.user = this.$getSessionStorage('user');
    
    // 验证用户信息
    if (!this.user?.userId) {
      this.$router.push('/login');
      return;
    }
    
    this.listDeliveryAddressByUserId();
  },
  components: {
    Footer
  },
  filters: {
    sexFilter(value) {
		console.log('过滤器被调用，值:', value, '类型:', typeof value);
      // 修改为直接显示男女，而不是先生女士
      return value == 1 ? '男' : '女';
    }
  },
  methods: {
    // 获取用户配送地址列表
    async listDeliveryAddressByUserId() {
      try {
        const response = await this.$axios.get('/api/addresses', {
          params: {
            userId: this.user.userId
          }
        });
        
        if (response.data.success) {
          this.deliveryAddressArr = response.data.data || [];
        } else {
          console.error('获取地址列表失败:', response.data.message);
          this.deliveryAddressArr = [];
          alert('获取地址列表失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('请求地址列表失败:', error);
        this.deliveryAddressArr = [];
        this.handleApiError(error, '获取地址列表');
      }
    },
    getGenderText(genderValue) {
      // 处理所有可能的格式
      if (genderValue === 1 || genderValue === '1') {
        return '男';
      } else if (genderValue === 0 || genderValue === '0') {
        return '女';
      } else {
        return ''; // 未知性别
      }
    },
    // 设置默认配送地址
    setDeliveryAddress(address) {
      // 存储到localStorage
      this.$setLocalStorage(this.user.userId, address);
      
      // 跳转到订单页面
      this.$router.push({
        path: '/orders',
        query: {
          businessId: this.businessId
        }
      });
    },
    
    // 跳转到新增地址页面
    toAddUserAddress() {
      this.$router.push({
        path: '/addUserAddress',
        query: {
          businessId: this.businessId
        }
      });
    },
    
    // 跳转到编辑地址页面
    editUserAddress(addressId) {
      this.$router.push({
        path: '/editUserAddress',
        query: {
          businessId: this.businessId,
          daId: addressId
        }
      });
    },
    
    // 删除配送地址
    async removeUserAddress(addressId) {
      if (!confirm('确认要删除此送货地址吗？')) {
        return;
      }
      
      try {
        const response = await this.$axios.delete(`/api/addresses/${addressId}`);
        
        if (response.data.success) {
          // 检查是否删除的是默认地址
          const defaultAddress = this.$getLocalStorage(this.user.userId);
          if (defaultAddress && defaultAddress.id === addressId) {
            this.$removeLocalStorage(this.user.userId);
          }
          
          // 刷新地址列表
          await this.listDeliveryAddressByUserId();
          alert('地址删除成功');
        } else {
          alert('删除地址失败: ' + (response.data.message || ''));
        }
      } catch (error) {
        console.error('删除地址失败:', error);
        this.handleApiError(error, '删除地址');
      }
    },
    
    // 统一的API错误处理方法
    handleApiError(error, operation) {
      console.error(`${operation}失败:`, {
        message: error.message,
        status: error.response?.status,
        data: error.response?.data
      });
      
      if (error.response?.status === 500) {
        alert('服务器内部错误，请稍后再试');
      } else if (error.response?.status === 404) {
        alert('请求的资源不存在');
      } else if (error.response?.status === 401) {
        alert('用户未登录或会话已过期');
        this.$router.push('/login');
      } else if (error.response?.data?.message) {
        alert(`${operation}失败: ${error.response.data.message}`);
      } else {
        alert(`${operation}失败，请检查网络连接`);
      }
    }
  }
}
</script>

<style scoped>
  /*************** 总容器 ***************/
  .wrapper {
    width: 100%;
    height: 100%;
    background-color: #F5F5F5;
  }

  /*************** header ***************/
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    display: flex;
    justify-content: space-around;
    align-items: center;
    color: #fff;
    font-size: 4.8vw;
    position: fixed;
    left: 0;
    top: 0;
    /*保证在最上层*/
    z-index: 1000;
  }

  /*************** addresslist ***************/
  .wrapper .addresslist {
    width: 100%;
    margin-top: 12vw;
    background-color: #fff;
  }

  .wrapper .addresslist li {
    width: 100%;
    box-sizing: border-box;
    border-bottom: solid 1px #DDD;
    padding: 3vw;
    display: flex;
  }

  .wrapper .addresslist li .addresslist-left {
    flex: 5;
    /*左边这块区域是可以点击的*/
    user-select: none;
    cursor: pointer;
  }

  .wrapper .addresslist li .addresslist-left h3 {
    font-size: 4.6vw;
    font-weight: 300;
    color: #666;
  }

  .wrapper .addresslist li .addresslist-left p {
    font-size: 4vw;
    color: #666;
  }

  .wrapper .addresslist li .addresslist-right {
    flex: 1;
    font-size: 5.6vw;
    color: #999;
    cursor: pointer;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }

  /*************** 新增地址部分 ***************/
  .wrapper .addbtn {
    width: 100%;
    height: 14vw;
    border-top: solid 1px #DDD;
    border-bottom: solid 1px #DDD;
    background-color: #fff;
    margin-top: 4vw;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 4.5vw;
    color: #0097FF;
    user-select: none;
    cursor: pointer;
  }

  .wrapper .addbtn p {
    margin-left: 2vw;
  }
</style>